# ~*~ coding: utf-8 ~*~
import datetime
from flask import request, views, render_template, send_from_directory, current_app, jsonify

from apps.perms.mixin import PermissionRequiredMixin, LoginRequiredMixin
from apps.common.utils import timestamp_obj_to_str
from apps.extensions import db
from ..models import Session

__all__ = ['SessionOnlineListAPI', 'SessionOfflineListAPI', 'SessionOnlineListView', 'SessionOfflineListView',
           'SessionRecordFileAPI', 'SessionReplayView']


class SessionOnlineListAPI(LoginRequiredMixin, PermissionRequiredMixin, views.MethodView):
    permission_required = 'terminal-session-online'

    def get(self):

        # 过滤
        filter_conditions = [
            ('is_finished', 'eq', False),
        ]

        # 排序
        sort = request.args.get('sort')
        order = request.args.get('order')
        order_by_list = [(sort, order), ]

        # 分页
        offset = request.args.get('offset') or 0
        limit = request.args.get('limit') or 12

        # Compatible with select2
        if request.values.get('type') == 'select2':
            filter_conditions = []
            order_by_list = None
            search = request.values.get('search')
            filter = request.values.get('filter')
            page = request.values.get('page')
            if search:
                filter_conditions.append(('name', 'like', search))
            if filter:
                filter_conditions.append(('id', 'in', filter.split(',')))
            if page:
                limit = 12
                offset = (int(page) - 1) * limit
            else:
                limit = None
                offset = 0

        sessions, count = Session.get_queryset(
            filter_conditions=filter_conditions,
            order_by_list=order_by_list,
            offset=offset, limit=limit
        )

        results = list()
        for session in sessions:
            results.append({
                'id': session.id,
                'user': session.user,
                'asset': session.asset,
                'system_user': session.system_user,
                'login_from': session.login_from,
                'remote_addr': session.remote_addr,
                'protocol': session.protocol,
                'record_path': session.record_path,
                'date_start': timestamp_obj_to_str(session.date_start),
                'date_end': '-',
                'exec_time': '-',
            })

        resp = {
            "data": {
                "rows": results,
                "total": count
            }
        }
        return jsonify(resp)


class SessionOfflineListAPI(LoginRequiredMixin, PermissionRequiredMixin, views.MethodView):
    permission_required = 'terminal-session-offline'

    def get(self):

        # 过滤
        filter_conditions = [
            ('is_finished', 'eq', True),
        ]

        # 排序
        sort = request.args.get('sort')
        order = request.args.get('order')
        order_by_list = [(sort, order), ]

        # 分页
        offset = request.args.get('offset') or 0
        limit = request.args.get('limit') or 12

        # Compatible with select2
        type = request.values.get('type')
        if type == 'select2':
            page = request.values.get('page')
            name = request.values.get('name')
            filter_conditions = [('name', 'like', name), ]
            order_by_list = None
            default_limit = 12
            offset = (int(page) - 1) * default_limit

        sessions, count = Session.get_queryset(
            filter_conditions=filter_conditions,
            order_by_list=order_by_list,
            offset=offset, limit=limit
        )

        results = list()
        for session in sessions:
            results.append({
                'id': session.id,
                'user': session.user,
                'asset': session.asset,
                'system_user': session.system_user,
                'login_from': session.login_from,
                'remote_addr': session.remote_addr,
                'protocol': session.protocol,
                'record_path': session.record_path,
                'exec_time': str(datetime.timedelta(seconds=session.date_end - session.date_start)),
                # 'exec_time': '{}秒'.format(session.date_end - session.date_start) if session.date_end else '0秒',
                'date_start': timestamp_obj_to_str(session.date_start),
                'date_end': timestamp_obj_to_str(session.date_end),
            })

        resp = {
            "data": {
                "rows": results,
                "total": count
            }
        }
        return jsonify(resp)


class SessionOnlineListView(LoginRequiredMixin, PermissionRequiredMixin, views.MethodView):
    permission_required = 'terminal-session-online'

    def get(self):
        return render_template('terminal/session_online.html')


class SessionOfflineListView(LoginRequiredMixin, PermissionRequiredMixin, views.MethodView):
    permission_required = 'terminal-session-offline'

    def get(self):
        return render_template('terminal/session_offline.html')


class SessionRecordFileAPI(LoginRequiredMixin, PermissionRequiredMixin, views.MethodView):
    """记录"""
    permission_required = 'terminal-session-replay'

    def get(self, filename):
        return send_from_directory(current_app.config.get('RECORDS_LOG_DIR'), filename)


class SessionReplayView(LoginRequiredMixin, PermissionRequiredMixin, views.MethodView):
    """回放"""
    permission_required = 'terminal-session-replay'

    def get(self, pk):
        instance = db.session.query(Session).get(pk)
        content = {
            'record_path': instance.record_path,
            'system_user': instance.system_user,
            'asset': instance.asset
        }
        return render_template('terminal/session_replay.html', **content)
